package com.smsc.headend.connector.runnable;

import com.smsc.headend.connector.builder.LoggerBuilder;
import com.smsc.headend.connector.netty.NettyConfigHelper;
import com.smsc.headend.connector.utils.NetUtil;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.TimerTask;


@AllArgsConstructor
@Slf4j
public class ResendPacketTask extends TimerTask {

    private Channel channel;
    private ByteBuf msg;


    @Override
    public void run() {
        String loggerName = channel.attr(NettyConfigHelper.comEntityAttrKey).get().getModuleSn();
        LoggerBuilder.getLogger(StringUtils.isEmpty(loggerName) ? "unknown-device" : loggerName, this.getClass()).info("start resend task to {}", NetUtil.getIpFromChannel(channel));
        ByteBuf duplicate = msg.copy();
        byte[] result = new byte[duplicate.readableBytes()];
        duplicate.readBytes(result);


        Integer retryTime = channel.attr(NettyConfigHelper.retryTimes).get();
        LoggerBuilder.getLogger(StringUtils.isEmpty(loggerName) ? "unknown-device" : loggerName, this.getClass()).info("--> :resend {}: {}",retryTime, ByteUtils.byteToHexString(result));
        channel.writeAndFlush(msg);
    }
}
